<script setup>
import { ref, reactive, computed, onMounted, h } from 'vue';
import { useBreadcrumbData } from '@/stores/breadcrumb'
import { doPost, downloadFile } from '@/http/api'
import { ElMessageBox, ElNotification } from 'element-plus'
import { genFileId } from 'element-plus'
import dayjs from 'dayjs'

// 面包屑数据
const breadcrumbList = ref([
  {
    name: '首页',
    routeName: 'homeData'
  },
  {
    name: '文件上传下载',
    routeName: ''
  },
]);

const uploadAction = import.meta.env.VITE_API_URL + "/upload";

const breadcrumbDataStore = useBreadcrumbData();
breadcrumbDataStore.setBreadcrumbData(breadcrumbList);

onMounted(() => {
  getTableData();
})

const pageData = reactive({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20, 200],
  total: 100,
});

const batchProgressShow = ref(false);
const batchProgressPercentage = ref(0);

const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  getTableData();
};

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  getTableData();
};

/*
 * 数据表格
 */
const multipleTableRef = ref();

const handleClick = (obj) => {
  let fileNameArr = getFileNameArr(obj);
  console.log(fileNameArr);
  if (fileNameArr.length == 0) {
    ElMessageBox({
      title: '提示',
      message: `请选择要下载的文件`,
      type: 'warning'
    }).then(() => {
    });
    return;
  }

  if (obj != "") {
    obj.show = true;
  }else{
    batchProgressShow.value = true;
  }

  downloadFile("/downloadFiles", { fileNameArr: fileNameArr }, downloadProgressCallback, obj).then(() => {
    console.log("下载完成===");
  });
}

const downloadProgressCallback = (event, obj) => {
  const percent = Math.round(event.loaded / event.total * 100);
    if (obj != "") {
      obj.percentage = percent;
    }else{
      batchProgressPercentage.value = percent;
    }

    if (percent == 100) {
      if (obj != "") {
        obj.show = false;
        obj.percentage = 0;
      }else{
        batchProgressPercentage.value = 0;
        batchProgressShow.value = false;
      }
    }
}

const handleDelete = (obj) => {
  ElMessageBox.confirm('此操作将永久删除文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let fileNameArr = getFileNameArr(obj);
    await deleteFile(fileNameArr);
    getTableData();
  })
}

const getFileNameArr = (obj) => {
  let fileNameArr = [];
  if (obj == "") {
    const ids = multipleTableRef.value.getSelectionRows();

    ids.forEach((item) => {
      fileNameArr.push(item.fileName);
    });

  } else {
    fileNameArr.push(obj.fileName);
  }
  return fileNameArr;
}

const deleteFile = async (obj) => {
  await doPost('/deleteFile', {
    fileNameArr: obj,
  })

  ElNotification({
    title: 'Title',
    message: h('i', { style: 'color: teal' }, '删除成功'),
  })

}

const tableData = reactive([
  {
    fileName: 'picture.jpg',
    size: '200',
    createTime: '2016-05-02',
  },
])

const getTableData = () => {
  // 请求数据
  doPost('/other/getFileTable', {
    pageSize: pageData.pageSize,
    currentPage: pageData.currentPage,
  }).then((res) => {
    pageData.total = res.total;
    tableData.splice(0, tableData.length, ...res.fileTableData);

    // 遍历tableData数组，为每个元素添加show和percentage属性
    tableData.forEach(item => {
      item.show = false; // 假设我们默认设置show为true
      item.percentage = 0; // 假设我们为每个文件设置一个默认的百分比，这里以50%为例
    });
  })
}

const handleSuccess = (response) => {
  if (response.retCode == "000000") {
    ElNotification({
      title: 'Title',
      message: h('i', { style: 'color: teal' }, '上传成功'),
    })
    getTableData();
  } else {
    ElMessageBox({
      title: '提示',
      message: `上传失败：${response.retMsg}`,
      type: 'warning'
    }).then(() => {
    });
  }
};

const handleError = (err, file) => {
  ElMessageBox({
    title: '提示',
    message: `上传失败：${err.retMsg}`,
    type: 'warning'
  }).then(() => {
  });
}

const handleExceed = (files, fileList) => {
  ElMessageBox.alert('最多只能上传9个文件', '提示', {
    confirmButtonText: '确定'
  });
};

</script>

<template>
  <main class="main">
    <el-row class="margin-top-bottom-10">
      <el-col :span="24" class="menu">
        <el-button type="primary" @click="getTableData">刷新</el-button>
        <el-button type="primary" @click="handleClick('')">下载</el-button>
        <el-button type="primary" @click="handleDelete('')">删除</el-button>
        <el-upload ref="upload" class="upload-demo" :action="uploadAction" multiple
          :limit="9" :on-exceed="handleExceed" :on-success="handleSuccess" :on-error="handleError"
          :show-file-list="false">
          <el-button type="primary">上传</el-button>
        </el-upload>
        <el-progress class="progress" v-if="batchProgressShow" :percentage="batchProgressPercentage"  />
      </el-col>
    </el-row>

    <el-table ref="multipleTableRef" :data="tableData">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="fileName" label="文件名" width="400" />
      <el-table-column prop="size" label="大小(K)" width="200" />
      <el-table-column prop="createTime" label="上传日期" width="250" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <div>
            <el-button link type="primary" size="small" @click="handleClick(scope.row)">下载</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </div>
          <div>
            <el-progress v-if="scope.row.show" :percentage="scope.row.percentage"  />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="margin-top-bottom-10">
      <el-pagination v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize"
        :page-sizes="pageData.pageSizes" layout="total, sizes, prev, pager, next, jumper" :total="pageData.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </main>
</template>

<style scoped >
.upload-demo {
  margin-left: 12px;
  display: inline;
}

.menu{
  display: flex;
}

.progress{
  flex: 1;
  margin-left: 12px;
}
</style>